package frame

import (
	"strconv"

	"github.com/gin-gonic/gin"
)

// Empty ...
var Empty = struct{}{}

// Page ...
type Page struct {
	Index int `json:"index"`
	Size  int `json:"size"`
}

// Offset ...
func (page *Page) Offset() int {
	if page.Index == 0 {
		return 0
	}
	return (page.Index - 1) * page.Size
}

// Limit ...
func (page *Page) Limit() int {
	return page.Size
}

//ParsePage if no page param, return nil
func ParsePage(ctx *gin.Context) *Page {
	indexPar := ctx.Query("page_index")
	index, _ := strconv.Atoi(indexPar)

	sizePar := ctx.Query("page_size")
	size, _ := strconv.Atoi(sizePar)

	if index == 0 && size == 0 {
		return nil
	}

	return &Page{
		Index: index,
		Size:  size,
	}
}

//MustPage if no page param, return a default page
func MustPage(ctx *gin.Context, defaultSize ...int) *Page {
	indexPar := ctx.Query("page_index")
	index, _ := strconv.Atoi(indexPar)
	if index == 0 {
		index = 1
	}

	sizePar := ctx.Query("page_size")
	size, _ := strconv.Atoi(sizePar)
	if size == 0 {
		if len(defaultSize) > 0 {
			size = defaultSize[0]
		} else {
			size = 20
		}
	}

	return &Page{
		Index: index,
		Size:  size,
	}
}
